

import 'package:alip_app/AppStates/NetworkApi.dart';
import 'package:alip_app/AppStates/UserState.dart';
import 'package:alip_app/HttpInterface.dart';
import 'package:alip_app/StateManagement/ModelProvider.dart';
import 'package:alip_app/UI/Widgets/Dialogs.dart';
import 'package:flare_dart/math/mat2d.dart';
import 'package:flare_flutter/flare.dart';
import 'package:flare_flutter/flare_actor.dart';
import 'package:flare_flutter/flare_controller.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';

class SignInPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _SignInPageState();
}

class _SignInPageState extends State<SignInPage> with SingleTickerProviderStateMixin {
  TabController _tabController;
  _SignInPageAnimationController _animationController = _SignInPageAnimationController();
  final _panelKey = GlobalKey();
  bool get isPageOne => _tabController.animation.value < 0.5;
  TextEditingController _signInNameController = TextEditingController();
  TextEditingController _signInPasswordController = TextEditingController();

  TextEditingController _signUpNameController = TextEditingController();
  TextEditingController _signUpPasswordController = TextEditingController();
  TextEditingController _signUpPasswordAgainController = TextEditingController();

  @override
  void initState() {
    this._tabController = TabController(length: 2, vsync: this);
    this._tabController.animation.addListener(this.swipeListener);
    SchedulerBinding.instance.addPostFrameCallback((timeStamp)async {
      final account = await ModelContainer.of<UserState>(context).model.getRememberedAccount() ?? WithPassword(password: "", userName: "");
      this._signInNameController.text = account.userName;
      this._signInPasswordController.text = account.password;
    });
    super.initState();
  }
  @override
  void dispose() {
    this._tabController.removeListener(this.swipeListener);
    super.dispose();
  }
  void swipeListener() {
    this._animationController.value = this._tabController.animation.value;
  }
  @override
  Widget build(BuildContext context) {
    Widget buildingWidget;
    buildingWidget = Scaffold(
      body: Stack(
        children: <Widget>[
          Positioned.fill(
            child: FlareActor("assets/animations/SignInPage.flr", animation: "Boot", fit: BoxFit.cover, controller: this._animationController,),
          ),
          Positioned.fill(
            child: _buildPanel(),
          ),
          Positioned.fill(
            child: TabBarView(
              controller: _tabController,
              children: <Widget>[
                Center(child: SizedBox(width: 250.0, child: _buildSignInPage(),),),
                Center(child: SizedBox(width: 250.0, child: _buildSignUpPage(),),),
              ],
            ),
          ),
          Positioned.fill(
            child: Center(
              child: _buildActionButtons(),
            ),
          ),
        ],
      ),
    );
    buildingWidget = Directionality(textDirection: TextDirection.rtl, child: buildingWidget);
    return buildingWidget;
  }

  Widget _buildSignInPage() {
    return StatefulBuilder(
      builder: (context, setState) => Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          SizedBox(height: 40.0, child: TextField(
            controller: _signInNameController,
            decoration: _getDefaultInputDecorations(context).copyWith(prefixIcon: Icon(Icons.person), hintText: "ئەزالىق نامىڭىز"),
            style: _getDefaultInputTextStyle(context),
            autofocus: false,
          ),),
          SizedBox(height: 20.0,),
          SizedBox(height: 40.0, child: TextField(
            controller: _signInPasswordController,
            obscureText: true,
            decoration: _getDefaultInputDecorations(context).copyWith(prefixIcon: Icon(Icons.vpn_key), hintText: "پارولىڭىز"),
            style: _getDefaultInputTextStyle(context),
            autofocus: false,
          ),),
        ],
      ),
    );
  }

  Widget _buildSignUpPage() {
    return StatefulBuilder(
      builder: (context, setState) => Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          SizedBox(height: 40.0, child: TextField(
            controller: _signUpNameController,
            decoration: _getDefaultInputDecorations(context).copyWith(prefixIcon: Icon(Icons.person), hintText: "ئەزالىق نامىڭىز"),
            style: _getDefaultInputTextStyle(context),
          ),),
          SizedBox(height: 20.0,),
          SizedBox(height: 40.0, child: TextField(
            controller: _signUpPasswordController,
            obscureText: true,
            decoration: _getDefaultInputDecorations(context).copyWith(prefixIcon: Icon(Icons.vpn_key), hintText: "پارولىڭىز"),
            style: _getDefaultInputTextStyle(context),
          ),),
          SizedBox(height: 20.0,),
          SizedBox(height: 40.0, child: TextField(
            controller: _signUpPasswordAgainController,
            obscureText: true,
            decoration: _getDefaultInputDecorations(context).copyWith(prefixIcon: Icon(Icons.vpn_key), hintText: "يەنە بىر قىتىم"),
            style: _getDefaultInputTextStyle(context),
          ),),
        ],
      ),
    );
  }

  InputDecoration _getDefaultInputDecorations(BuildContext context) {
    return InputDecoration(
      filled: true,
      fillColor: Theme.of(context).scaffoldBackgroundColor,
      enabledBorder: OutlineInputBorder(borderSide: BorderSide.none, borderRadius: BorderRadius.circular(15.0)),
      focusedBorder: OutlineInputBorder(borderSide: BorderSide(color: Theme.of(context).primaryColor.withOpacity(0.1)), borderRadius: BorderRadius.circular(15.0),),
      contentPadding: EdgeInsets.all(3.0),
      hintStyle: TextStyle(fontSize: 14.0, color: Theme.of(context).hintColor.withOpacity(0.3)),
    );
  }

  TextStyle _getDefaultInputTextStyle(BuildContext context) {
    return TextStyle(
      color: Theme.of(context).textTheme.bodyText2.color
    );
  }

  Widget _buildPanel() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
//        Transform.translate(
//          offset: Offset(0.0, -90.0),
//          child: Text("مەرھابا", style: Theme.of(context).textTheme.headline4),
//        ),
        SizedBox(height: 30.0,),
        AnimatedBuilder(
          animation: _tabController.animation,
          builder: (context, child) {
            return Container(
              key: _panelKey,
              width: 300.0,
              height: 300.0 + _tabController.animation.value * 100,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(15.0),
                  color: Theme.of(context).backgroundColor
              ),
            );
          },
          child: Transform.translate(
            offset: Offset(0.0, -64.0),
            child: CircleAvatar(
              backgroundColor: Theme.of(context).scaffoldBackgroundColor,
              radius: 64.0,
              backgroundImage: AssetImage("assets/images/avatar.png"),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildActionButtons() {
    return AnimatedBuilder(
      animation: _tabController.animation,
      builder: (context, child) {
        return SizedBox(
          width: 300.0,
          height: 300.0 + _tabController.animation.value * 100,
          child: Column(
            children: <Widget>[
              child,
              Spacer(),
              RaisedButton(
                  color: Theme.of(context).primaryColor,
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(13.0)),
                  child: Text(isPageOne ? "كىرىڭ" : "تىزىملىتىڭ", style: TextStyle(color: Theme.of(context).scaffoldBackgroundColor),),
                  onPressed: () async {
                    final result = await Dialogs.runWithProgressDialog(context: context, action: () => ModelContainer.of<UserState>(context).model.signIn(context, WithPassword(
                      userName: _signInNameController.text,
                      password: _signInPasswordController.text,
                    )),);
                    if (result == null) return;
                    print(result.toJson());
                    Navigator.of(context).pop();
                  }
              ),
              Text(isPageOne ? "ھىساباتىڭىز يوقمۇ؟" : "ھىساباتىڭىز بارمۇ؟", style: TextStyle(fontStyle: FontStyle.italic),),
              InkWell(
                child: Text(isPageOne ? "يىڭىدىن بىرنى قۇرۇڭ" : "بۇ يەردىن كىرىڭ", style: TextStyle(color: Theme.of(context).primaryColor, decoration: TextDecoration.underline),),
                onTap: ()async {
                  this._tabController.animateTo(isPageOne ? 1 : 0);
                },
              ),
            ],
          ),
        );
      },
      child: Transform.translate(
        offset: Offset(0.0, -64.0),
        child: CircleAvatar(
          backgroundColor: Theme.of(context).scaffoldBackgroundColor,
          radius: 64.0,
          backgroundImage: AssetImage("assets/images/avatar.png"),
        ),
      ),
    );
  }
}

class _SignInPageAnimationController extends FlareController {
  ActorAnimation _switchAnimation;
  ActorAnimation _bootAnimation;
  double _value = 0.0;
  _SignInPageAnimationController();

  @override
  bool advance(FlutterActorArtboard artboard, double elapsed) {
    final time = _switchAnimation.duration * this.value;
    this._switchAnimation.apply(time, artboard, 0.1); //17899255489
    this.isActive.value = false;
    return true;
  }

  @override
  void initialize(FlutterActorArtboard artboard) {
    // TODO: implement initialize
    this._switchAnimation = artboard.getAnimation("Switch");
    this._bootAnimation = artboard.getAnimation("Boot");
  }

  @override
  void setViewTransform(Mat2D viewTransform) {
    // TODO: implement setViewTransform
  }
  double get value => _value;
  set value(double __value) {
    _value = __value;
    this.isActive.value = true;
  }
}